<template>
  <div class="home-container">
    <!--    账号管理内容-->
    <div class="top-container">
      <el-button type="primary" @click="handleAdd">添加账号</el-button>
    </div>
    <!--    table组件-->
    <el-table :data="accountData" v-loading="accountLoading" border style="width: 100%">
      <el-table-column prop="username" label="账号" width="180" />
      <el-table-column label="密码" width="180">
        <template #default="scope"> ****** </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button link type="primary" :icon="Edit" @click="handleUpdate(scope)"
            >修改密码</el-button
          >
          <!-- <el-button link type="danger" :icon="Delete" @click="handleDelete(scope)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <!--    添加账号对话框-->
    <el-dialog v-model="addDialogVisible" title="添加账号" width="500" align-center>
      <el-form
        style="max-width: 500px"
        :model="accountForm"
        :rules="rules"
        label-width="auto"
        ref="formRef"
      >
        <el-form-item label="账号">
          <el-button type="primary" plain @click="demoo" style="width: 420px">{{
            accountForm.username == ""
              ? "请选择账号"
              : `${selectName}: ${accountForm.username}`
          }}</el-button>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="accountForm.password" />
        </el-form-item>
        <el-form-item class="button-content">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="onAddSubmit">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--    部门和人员选择对话框-->
    <el-dialog
      v-model="addPeoplefalck"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="true"
      title="选择部门与人员"
      center
      width="560"
    >
      <div class="dialog">
        <div class="dialog-left">
          <div class="left">
            <!-- 树形组件 -->
            <el-table
              v-loading="departmentStore.loading"
              :data="departmentStore.departmentList"
              element-loading-text="加载中..."
              row-key="selfid"
              border
              default-expand-all
              :tree-props="{ children: 'childs', hasChildren: 'hasChildren' }"
              style="height: 100%; overflow: hidden"
            >
              <OrganizationNameColumn
                v-if="drawerVisible"
                selectable="false"
                hoverable="true"
                @select="selectNode"
                widths="50px"
              />
            </el-table>
          </div>
        </div>
        <div class="dialog-right">
          <el-table
            ref="employeeTable"
            :data="employeeData"
            style="width: 100%"
            @cell-click="handleSelectionChange"
          >
            <el-table-column type="index" width="20" />
            <el-table-column prop="staffPhoto" align="center" label="头像">
              <template v-slot="{ row }">
                <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
                <span v-else class="username">{{ row.username.charAt(0) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="username" label="姓名" />
          </el-table>
        </div>
      </div>
    </el-dialog>

    <!--    编辑对话框-->
    <el-dialog v-model="editDialogVisible" title="编辑账号" width="500" align-center>
      <el-form
        style="max-width: 500px"
        :model="editForm"
        label-width="auto"
        ref="editFormRef"
        :rules="rules"
      >
        <el-form-item label="账号" prop="username">
          <el-input disabled v-model="editForm.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="editForm.password" />
        </el-form-item>
        <!--        <el-form-item label="备注">-->
        <!--          <el-input v-model="editForm.remark" />-->
        <!--        </el-form-item>-->
        <el-form-item>
          <div class="button-content">
            <el-button @click="editDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="onEditSubmit">确定</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--    删除对话框-->
    <!-- <el-dialog v-model="deleteDialogVisible" title="警告" width="500" align-center>
      <span>是否确定删除该账号？</span>
      <template #footer>
        <div>
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleDeleteDialog"> 确定 </el-button>
        </div>
      </template>
    </el-dialog> -->
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from "vue";
import { Delete, Edit, View, Hide } from "@element-plus/icons-vue";
import { ElForm, ElFormItem, ElInput, ElButton, ElMessage } from "element-plus";
import {
  getAccountList,
  valAccountList,
  updateAccountList,
  addAccountList,
} from "@/api/account";

import { getDepartmentList } from "@/api/department";
import { getUserInfo } from "@/api/employee";

import { useDepartmentStore } from "@/stores/department";

const departmentStore = useDepartmentStore();

const accountData = ref(<Array<unknown> | any>[]);
const initialData = ref(<Array<unknown> | any>[]);
const accountForm = reactive(<object | any>{
  username: "",
  password: "",
});
const editForm = reactive(<object | any>{
  username: "",
  password: "",
});
const deleteDialogVisible = ref(<Boolean>false);
const addDialogVisible = ref(<Boolean>false);
const editDialogVisible = ref(<Boolean>false);
const accountLoading = ref(<Boolean>true);
// 表单引用
const formRef = ref<InstanceType<typeof ElForm>>();
const editFormRef = ref<InstanceType<typeof ElForm>>();

// 练级选择器

const demoo = () => {
  addPeoplefalck.value = !addPeoplefalck.value;
  drawerVisible.value = true;
};

const drawerVisible = ref(false);

const addPeoplefalck = ref(false);

//左边显示员工数据
const employeeData = ref(<Array<unknown> | any>[]);

// 存储查询参数，记录节点
const queryParams = reactive({
  id: 0,
  page: 1, //当前页
  pagesize: 10,
  keyword: "",
});
const employeeTable = ref(null); // 为 el-table 绑定 ref

//切换节点
const selectNode = async (node: any) => {
  queryParams.id = node.selfid; //重新记录参数
  queryParams.page = 1; //设置第一页
  getUserData();
};
//获取员工表格数据
const getUserData = async () => {
  const res = await getUserInfo(queryParams.id);
  employeeData.value = [];
  res.data.forEach((item: any) => {
    if (item.userid != null && item.userid != " ") {
      employeeData.value.push(item);
    }
  });
};

const selectName = ref("");

//人员表格选择监听
const handleSelectionChange = (selection: any, row: any) => {
  if (selection != null && selection != "" && selection != undefined) {
    accountForm.username = selection.email;
    selectName.value = selection.username;
    addPeoplefalck.value = false;
  }
};

// 表单验证规则
const rules = reactive({
  username: [{ required: true, message: "账号不能为空", trigger: "blur" }],
  password: [
    { required: true, message: "密码不能为空", trigger: "blur" },
    { min: 6, max: 20, message: "密码长度应为6到20个字符", trigger: "blur" },
  ],
  remark: [{ max: 100, message: "备注长度不能超过100个字符", trigger: "blur" }],
});

//初始化数据时，密码加密showPassword字段添加到数组中
onMounted(async () => {
  await departmentStore.fetchDepartmentList();

  await getData();
});
const getData = async () => {
  // 后端返回的数据
  const res = await getAccountList();
  accountLoading.value = false;
  initialData.value = res.data.info_list;
  accountData.value = initialData.value.map((item: any) => ({
    ...item,
    showPassword: false,
  }));
};

// 密码过滤器
const passwordFilter = (password: string) => {
  // return '•'.repeat(password.length);
};
// 切换密码显示状态
const togglePasswordVisibility = (index: number) => {
  accountData.value[index].showPassword = !accountData.value[index].showPassword;
};
//添加账号
const handleAdd = async () => {
  accountForm.username = "";
  accountForm.password = "";
  addDialogVisible.value = true;
};
//修改密码
const handleUpdate = async (row: any) => {
  editForm.username = "";
  editForm.username = row.row.username;
  editForm.password = "";
  editDialogVisible.value = true;
};
// //删除
// const handleDelete = (row: object) => {
//   deleteDialogVisible.value = true;
// };
//修改密码对话框确定按钮
const onEditSubmit = async () => {
  editFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      // 这里可以添加修改密码的逻辑
      const res = await valAccountList(editForm.username);

      const isExist = res.data.is_exist;
      if (isExist == "true") {
        const resda = await updateAccountList(editForm);
        if (resda.code == "200") {
          ElMessage.success(resda.msg);
          editDialogVisible.value = false;
          getData();
        } else {
          ElMessage.error(resda.msg);
        }
      } else {
        ElMessage.warning("账号不存在");
      }
    } else {
      ElMessage.error("表单验证失败，请检查输入");
    }
  });
};
//添加对话框确定按钮
const onAddSubmit = async () => {
  if (
    accountForm.username == null ||
    accountForm.username == undefined ||
    accountForm.username == ""
  ) {
    ElMessage.warning("请选择账号");
    return;
  }
  // await addAccountList(accountForm);
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      const res = await addAccountList(accountForm);
      if (res.code == '200') {
        ElMessage.success("添加成功");
      } else {
        ElMessage.error(res.msg);
      }

      addDialogVisible.value = false;
      getData();
    } else {
      ElMessage.error("表单验证失败，请检查输入");
    }
  });
};
// //删除对话框确定按钮
// const handleDeleteDialog = () => {
//   //发请求

//   //刷新页面，弹出框关闭

//   deleteDialogVisible.value = false;
// };
</script>

<style lang="scss" scoped>
.home-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  .top-container {
    margin: 20px 0;
  }
  .password-cell {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .password-cell span {
      flex-grow: 1;
      text-align: left;
    }

    .password-cell .el-button {
      margin-left: 10px;
    }
  }
}
.button-content {
  margin-left: 300px;
}
.form-section {
  margin-bottom: 24px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;

  .section-title {
    font-size: 14px;
    font-weight: 700;
    color: #303133;
    margin-bottom: 16px;
  }

  .section-content {
    font-size: 14px;
    color: gray;
  }

  .section-tip {
    font-size: 12px;
    color: #909399;
    margin: -8px 0 16px 120px;
  }

  :deep(.el-form-item:last-child) {
    margin-bottom: 0;
  }
}

.drawer-form {
  padding: 20px;

  :deep(.el-form-item) {
    margin-bottom: 22px;
  }
}

.drawer-footer {
  position: absolute;
  right: 0;
  bottom: 0;
  left: 0;
  padding: 16px 20px;
  background: #fff;
  border-top: 1px solid #dcdfe6;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

// 修改抽屉自定义样式

.username {
  display: inline-block;
  width: 30px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  background-color: lightblue;
  border-radius: 50%;
  font-size: 14px;
  color: #909399;
}

.dialog {
  height: 380px;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
}

.dialog-left {
  height: 350px;
  width: 220px;
  transform: scale(1);
  overflow-y: auto;
  /* 添加垂直滚动条 */
  border: 1px solid #dcdfe6;
  /* 可选：添加边框以区分容器 */
  background-color: #fff;
  /* 可选：设置背景颜色 */
}

.dialog-leftqw,
.dialog-right {
  height: 350px;
  width: 300px;
  overflow-y: auto;
  /* 添加垂直滚动条 */
  border: 1px solid #dcdfe6;
  /* 可选：添加边框以区分容器 */
  background-color: #fff;
  /* 可选：设置背景颜色 */
}

.dialog-leftqw {
  margin-left: 40px;
}

.button-content {
  display: flex;
  flex-direction: row;
  justify-content: right;
}

.renyuan {
  cursor: not-allowed;
  background-color: #f5f7fa;
  margin-top: 8px;
  border: 1px solid #e8e8e8;
  padding-left: 8px;
  padding-right: 8px;
  height: 40px;
  width: 350px;
  line-height: 40px;
  border-radius: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 确保表格内容不会超出容器 */
.el-table {
  height: 100%;
  overflow: hidden;
}

/* 自定义滚动条样式 */
.dialog-left,
.dialog-right {
  scrollbar-width: thin;
  /* Firefox */
  scrollbar-color: #ccc #f1f1f1;
  /* Firefox */
}

.dialog-left::-webkit-scrollbar,
.dialog-right::-webkit-scrollbar {
  width: 8px;
}

.dialog-left::-webkit-scrollbar-thumb,
.dialog-right::-webkit-scrollbar-thumb {
  background-color: #ccc;
  border-radius: 4px;
}

.dialog-left::-webkit-scrollbar-track,
.dialog-right::-webkit-scrollbar-track {
  background-color: #f1f1f1;
}
</style>
